<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { userService } from '@/service';
import {generateRandomValue} from "@/utils/CommonUtil.ts";
import QRCode from 'qrcode'
import UserAgreement from '@/views/common/UserAgreement.vue';
import { queryLoginStatus } from '@/service/module/userService.ts';
const router = useRouter();
const route = useRoute();

const gzhQrCode = ref();
const sceneKey = ref('');

const agreed = ref(true);
const userAgreementRef = ref();

onMounted(() => {
  sceneKey.value = initSceneKey();
  queryGzhQrCode();
});

let timerId:any;
async function queryGzhQrCode() {
  const res = await userService.queryGzhQrCode(sceneKey.value,route.query.inviteCode as string);
  if (res.success) {
    QRCode.toDataURL(res.result)
      .then(code => {
        gzhQrCode.value = code;
      }).catch(err => {
      console.error(err)
    })
    timerId = setInterval(queryLoginStatus, 2000);
  } else {
    ElMessage.error(res.errorMsg);
  }
}

async function queryLoginStatus() {
  const res = await userService.queryLoginStatus(sceneKey.value);
  if (res.success) {
    if(res.result !== null) {
      window.localStorage.setItem("NickName", res.result.nickName);
      window.localStorage.setItem("InviteCode", res.result.inviteCode);
      window.localStorage.setItem("Authorization", res.result.token);
      clearInterval(timerId);
      await router.push({name: 'home'});
    }
  } else {
    ElMessage.error(res.errorMsg);
  }
}

function initSceneKey() {
  return generateRandomValue(16);
}

function openUserAgreement(){
  if (userAgreementRef.value) {
    userAgreementRef.value.openUserAgreementDialog();
  }
}

</script>

<template>
  <div class="login">
    <div class="gzh-content">
      <div class="title">微信扫描二维码登录</div>
      <img :src="gzhQrCode" alt="">
    </div>
    <div>
      <el-checkbox v-model="agreed" style="margin-right: 8px;"/>
      <span>我已阅读并同意<a @click="openUserAgreement" class="agreement">《用户服务许可协议》</a></span>
    </div>
  </div>
  <UserAgreement ref="userAgreementRef"/>
</template>

<style lang="less" scoped>

.login{
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  margin: 0 auto;
  height: 300px;
  width: 400px;
  text-align: center;
}

.gzh-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .title{
    font-size: 20px;
  }
}

.agreement{
  color: var(--el-color-primary);
  cursor: pointer;
}
</style>
